﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Enum;

namespace Matrix.MaKaYunShang.McMagWeb.Controllers
{
    public class CardRuleController : BaseController
    {
        [Authorization]
        public ActionResult Index()
        {
            var shops = ShopsBLL.Instance.GetModel(CurrentUser.ShopId);
            var cloudCardsList = CloudCardsBLL.Instance.GetModelList("(ShopId=" + CurrentUser.ShopId + ") and PassStatus=" + (int)CloudCardEnum.CloudCardsPassStatus.审核通过);
            ViewBag.CloudCardsList = cloudCardsList;
            var cardRuleBaseList = CardRuleBaseBLL.Instance.GetModelList("ShopId=" + CurrentUser.ShopId + " and EndTime>'" + DateTime.Now + "'").OrderBy(l => l.AddTime).ToList();
            foreach (var item in cardRuleBaseList)
            {
                var ruleDetailList = CardRuleDetailBLL.Instance.GetModelList("RuleBaseId=" + item.Id);
                string conent = "";
                conent += ruleDetailList.Aggregate(conent + "[",
                    (current, item2) =>
                        current + ("{\"CloudCardId\":" + item2.CloudCardId + ",\"CardTotalQuantity\":" + item2.CardTotalQuantity + "},"
                            ));
                conent = conent.TrimEnd(',');

                conent += "]";
                item.IsNow = item.StartTime <= DateTime.Now;
                item.RuleDetailString = conent;
            }
            return View(cardRuleBaseList);
        }


        [HttpPost]
        public JsonResult SaveCardRule(string modelStr)
        {
            var result = new Result();
            var now = DateTime.Now;
            var cardRuleBaseList = JsonTool.JsonToObj<List<CardRuleBase>>(modelStr);
            if (cardRuleBaseList == null)
            {
                result.Message = "请添加数据!";
                return Json(result);
            }
            if (cardRuleBaseList.Count > 0)
            {
                cardRuleBaseList.ForEach(l => l.EndTime = l.EndTime.AddHours(23).AddMinutes(59).AddSeconds(59));
                cardRuleBaseList = cardRuleBaseList.FindAll(
                                    l => l.EndTime > now).ToList();
                var shopIinfo = ShopSubsidiaryInfoBLL.Instance.GetModelByShopId(CurrentUser.ShopId);
                var lastOrDefault = cardRuleBaseList.LastOrDefault();
                if (lastOrDefault != null)
                {
                    var cardTotalQuantity = lastOrDefault.RuleDetailList.Sum(s => s.CardTotalQuantity);
                    if (shopIinfo == null || (shopIinfo.TotalCanSendCard - shopIinfo.AlreadySendCard) < cardTotalQuantity)
                    {
                        result.Message = "余额不足请充值!";
                        return Json(result);
                    }
                }
                var nowCardRuleBaseList = CardRuleBaseBLL.Instance.GetModelList("ShopId=" + CurrentUser.ShopId + " and EndTime>'" + now + "'").OrderBy(l => l.StartTime).ToList();
                foreach (var item in nowCardRuleBaseList)
                {
                    if (CardRuleBaseBLL.Instance.Delete(item.Id))
                    {
                        CardRuleDetailBLL.Instance.DeleteByRuleBaseId(item.Id);
                    }
                }
                foreach (var item in cardRuleBaseList)
                {
                    item.ShopId = CurrentUser.ShopId;
                    item.AddTime = now;
                    item.AddMerchantUserId = CurrentUser.ShopId;
                    var newTimeSpanId = CardRuleBaseBLL.Instance.Add(item);
                    if (newTimeSpanId > 0)
                    {
                        foreach (var subItem in item.RuleDetailList)
                        {
                            subItem.RuleBaseId = newTimeSpanId;
                            subItem.AddTime = now;
                            CardRuleDetailBLL.Instance.Add(subItem);
                        }
                    }
                }
                result.Status = true;
            }
            if (!result.Status && string.IsNullOrEmpty(result.Message))
            {
                result.Message = "操作失败，请重试！";
            }
            return Json(result);
        }
        /// <summary>
        /// 删除时间段
        /// </summary>
        [HttpPost]
        public JsonResult DeleteCardRuleBase(int cardRuleBaseId)
        {
            var result = new Result();
            var cardRuleBaseModel = CardRuleBaseBLL.Instance.GetModel(cardRuleBaseId);
            if (cardRuleBaseModel != null && cardRuleBaseModel.ShopId == CurrentUser.ShopId)
            {
                result = new Result { Status = CardRuleBaseBLL.Instance.Delete(cardRuleBaseId) };
                if (result.Status)
                {
                    //删除时间段的卡券设置
                    CardRuleDetailBLL.Instance.DeleteByRuleBaseId(cardRuleBaseId);
                }
            }
            return Json(result);
        }

        /// <summary>
        /// 获取时间段已发卡券数量
        /// </summary>
        [HttpPost]
        public JsonResult GetCardsUseCount(int cardRuleBaseId)
        {
            var cardRuleBaseModel = CardRuleBaseBLL.Instance.GetModel(cardRuleBaseId);
            if (cardRuleBaseModel != null && cardRuleBaseModel.ShopId == CurrentUser.ShopId)
            {
                return Json(new Result<List<CardRuleDetail>>
                {
                    Data = CardRuleDetailBLL.Instance.GetModelList("RuleBaseId=" + cardRuleBaseId),
                    Status = true
                });
            }
            return Json(null);
        }
    }
}